package com.changgou.business.listener;


import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 大广告数据预热的MQ消费者监听器
 */
@Component
@RabbitListener(queues = "ad_update_queue")
public class AdUpdateListener {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @RabbitHandler
    public void msgHandle(String position){
        //1.拼接大广告缓存预热的URL
        String url = "http://192.168.200.128/ad_update?position="+position;

        //2.构建请求对象
        Request request = new Request.Builder().url(url).build();

        //3.执行请求大广告缓存预热的URL，此请求会被nginx接收处理
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);

        //4.获取请求结果并处理
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.info("大广告预热处理失败,广告分类是:{}",position);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.info("大广告预热处理成功,广告分类是:{}",position);
            }
        });

    }
}
